﻿using System.Linq;
using System.Web.Mvc;
using JStore.Core.Commands;
using JStore.Core.Entities;
using JStore.Tasks;
using JStore.Web.Controllers.UserTypeJdRateConfigs.ViewModels;
using SpeadFrm.Mappers;

namespace JStore.Web.Controllers.UserTypeJdRateConfigs
{
    public class UserTypeJdRateConfigsController : BaseController
    {
        private readonly UserTypeJdRateConfigTask _userTypeJdRateConfigTask = new UserTypeJdRateConfigTask();

        public ActionResult Save(int userTypeId)
        {
            var list = _userTypeJdRateConfigTask.GetListByUserTypeId(userTypeId)
                .Select(EntityMapper.Map<UserTypeJdRateConfig, UserTypeJdRateConfigModel>)
                .ToList();

            ViewData["list"] = list;

            var model = new SaveUserTypeJdRateConfigModel { UserTypeId = userTypeId };
            return View(model);
        }

        [HttpPost]
        public ActionResult Save(SaveUserTypeJdRateConfigModel model)
        {
            if (ModelState.IsValid)
            {
                var cmd = EntityMapper.Map<SaveUserTypeJdRateConfigModel, SaveUserTypeJdRateConfigCmd>(model);
                string errMsg;
                if (!_userTypeJdRateConfigTask.Save(cmd, out errMsg))
                    return AlertMsg(errMsg, Request.UrlReferrer.PathAndQuery);
                return AlertMsg("保存成功", Request.UrlReferrer.PathAndQuery);
            }
            return AlertMsg("参数异常", Request.UrlReferrer.PathAndQuery);
        }

        [HttpPost]
        public void Delete(int id)
        {
            _userTypeJdRateConfigTask.DeleteById(id);
        }
    }
}